package com.example.myhotel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.myhotel.common.BaseContext;
import com.example.myhotel.common.R;
import com.example.myhotel.common.UserThreadLocal;
import com.example.myhotel.dto.BookDto;
import com.example.myhotel.entity.Bill;
import com.example.myhotel.entity.Book;
import com.example.myhotel.entity.Customers;
import com.example.myhotel.entity.Rooms;
import com.example.myhotel.service.BillService;
import com.example.myhotel.service.BookService;
import com.example.myhotel.service.CustomersService;
import com.example.myhotel.service.RoomsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("book")
@CrossOrigin
public class BookController {
    @Autowired
    private RoomsService roomsService;
    @Autowired
    private CustomersService customersService;
    @Autowired
    private BillService billService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private BookService bookService;
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize){
        Page<Book> bookPage = new Page<>(page,pageSize);
        Page<BookDto> bookDtoPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        String userId = BaseContext.getCurrentId();

        long id = Thread.currentThread().getId();
        log.error("线程id为：{}",id);
        log.error(userId);

        wrapper.eq(userId != null,Book::getCustomerId,userId);
        wrapper.orderByDesc(Book::getBookTime);
        bookService.page(bookPage, wrapper);
        //对象拷贝
        BeanUtils.copyProperties(bookPage,bookDtoPage,"records");
        List<Book> records = bookPage.getRecords();
        List<BookDto> list = records.stream().map(item -> {
            BookDto bookDto = new BookDto();
//            拷贝属性
            BeanUtils.copyProperties(item,bookDto);
            String roomId = bookDto.getRoomId();
            String customerId = bookDto.getCustomerId();
            Customers user = customersService.getById(customerId);
            //获取房间信息
            Rooms room = roomsService.getById(roomId);
            //写入信息
            bookDto.setAddress(room.getAddress());
            bookDto.setMoney(room.getPrices());
            bookDto.setName(user.getName());
            return bookDto;
        }).collect(Collectors.toList());
        bookDtoPage.setRecords(list);
        //输出到前端
        return R.success(bookDtoPage);
    }
    @PostMapping()
    public R<String> book(@RequestBody Map map){
        LambdaQueryWrapper<Rooms> wrapper = new LambdaQueryWrapper<>();
        //时间格式
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String roomId = map.get("roomId").toString();
        String time = map.get("bookTime").toString();
        //字符串转为LocalDateTime
        LocalDateTime bookTime = LocalDateTime.parse(time,df);
//        String userId = map.get("userId").toString();
        String userId = BaseContext.getCurrentId();

        Rooms room = roomsService.getById(roomId);
        if (room.getCount()<=0){
            return R.error("对不起房间已被预定完了");
        }
        if (bookService.addBook(bookTime, userId, roomId)){
//            billService.addBill(roomId,userId);
            room.setCount(room.getCount()-1);
            roomsService.updateById(room);
            return R.success("成功预定");
        }else {
            return R.error("你已预定了一个房间");
        }
    }
    @PutMapping
    public R<String> celBook(@RequestBody Book book){
        book.setState(1);
        book.setEndTime(LocalDateTime.now());
        //添加会一个房间数
        Rooms room = roomsService.getById(book.getRoomId());
        room.setCount(room.getCount()+1);
        Long end = book.getEndTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        Long book1 = book.getBookTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        if (book1-end<=(2*60*60*1000)){
            return R.error("抱歉，仅可以在两小时前取消");
        }
        roomsService.updateById(room);
        //查看是否为已完成预定//未刷前要做的
        Book one = bookService.getById(book.getId());
        if (one.getState() == 2){
            return R.error("您已入住旅馆，不能取消预定");
        }

        bookService.updateById(book);

        return R.success("取消成功");
    }
    @DeleteMapping
    public R<String> delBook(String id){
        bookService.removeById(id);
        return R.success("删除成功");
    }



}
